import axios from 'axios'
import {ElMessage} from "element-plus";
import storage from '@/utils/storage'
import loading from "@/utils/loading";
const base_url = import.meta.env.VITE_BASE_URL_LOCAL
const request_timeout = import.meta.env.VITE_REQUEST_TIMEOUT

// 创建axios实例
const service = axios.create({
    baseURL: base_url, // api 的 base_url
    timeout: 60000000000000, // 请求超时时间
    withCredentials: false // 禁用 Cookie
})

/**
 * 请求拦截器
 */
service.interceptors.request.use(
    (config) => {
        // 配置请求头
        config.headers.token = storage.get('token')
        config.headers.user_id = storage.get('userInfo','json')?storage.get('userInfo','json').id : null
        config.headers.authorization = true

        loading.show()
        return config
    },
    (error) => {
        console.error('网络错误，请稍后重试')
        loading.hidden()
        return Promise.reject(error)
    }
)

/**
 * 响应拦截器
 */
service.interceptors.response.use(
    (response) => {
        // 响应处理，如状态码
        let data = response.data
        if (data.code === 500) {
            ElMessage.error(data.msg)
            loading.hidden()
            return Promise.reject(data.msg)
        } else if (data.code === 401) {
            localStorage.clear()
            location.reload()
            loading.hidden()
            return ElMessage.error(data.msg)
        }
        loading.hidden()
        return response.data
    },
    (error) => {
        loading.hidden()
        return Promise.reject(error)

    }
)

export default service
